If you use std::unique_ptr<T> const &
for a function parameter type, it means that the function will not be able to alter
the ownership of the pointed-to object by the unique_ptr
:
- It cannot acquire ownership of the pointed-to object (this would require a parameter of type
std::unique_ptr<T>
)
- It cannot transfer the object ownership to someone else (this would require a
std::unique_ptr<T> &
).
That means the function can only observe the pointed-to object, and in this case, passing a T*
(if the unique_ptr
can be
null) or a T&
(if it cannot) provides the same features, while also allowing the function to work with objects that are not handled
by a unique_ptr
(e.g., objects on the stack, in a vector
, or in another kind of smart pointer), thus making the function
more general-purpose.
Noncompliant code example
void draw(std::unique_ptr<Shape> const &shape); // Noncompliant
void drawAll(std::vector<std::unique_ptr<Shape>> v)
{
for (auto &shape : v) {
if (shape) {
draw(shape);
}
}
}
Compliant solution
void draw(Shape const &shape); // Compliant
void drawAll(std::vector<std::unique_ptr<Shape>> v)
{
for (auto &shape : v) {
if (shape) {
draw(*shape);
}
}
}